/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.eascs.log.util;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.log.dao.LogDao;
import com.eascs.log.entity.Log;
import com.eascs.web.sso.UserHolder;

/**
 * 日志
 */
@Service
public class LogUtils {
	
	Logger logger = LoggerFactory.getLogger(LogUtils.class);
	
	ExecutorService executorService = Executors.newFixedThreadPool(10);
	
	@Autowired
	private  LogDao logDao;
	
	/**
	 * 保存日志
	 */
	public void saveLog(HttpServletRequest request, Object handler, Exception ex){
		com.eascs.web.sso.User user = UserHolder.getUser();
		if (user != null && user.getNo() != null){
			Log log = new Log();
			log.setOpId(user.getNo());
			log.setOpName(user.getCname());
			log.setOpTime(new Date());
			log.setIsSuccess(ex == null ? StatusContexts.LOG_ACCESS : StatusContexts.LOG_EXCEPTION);
			log.setRemoteAddr(com.eascs.admin.common.utils.StringUtils.getRemoteAddr(request));
			log.setUserAgent(request.getHeader("user-agent"));
			log.setRequestUri(request.getRequestURI());
			log.setParams(request.getParameterMap());
			log.setMethod(request.getMethod());
			// 异步保存日志
			executorService.submit(new SaveLogRunnable(log,ex));
		}
	}

	/**
	 * 保存日志线程
	 */
	public  class SaveLogRunnable implements Runnable{
		
		private Log log;
		private Exception ex;
		
		public SaveLogRunnable(Log log, Exception ex){
			this.log = log;
			this.ex = ex;
		}
		
		@Override
		public void run() {
			// 如果有异常，设置异常信息
			log.setException(Exceptions.getStackTraceAsString(ex));
			// 保存日志信息
			logDao.insert(log);
		}
	}
}
